package thread;

/*
 * @author zzr
 * @date: 2025/04/08  19:37
 * @description:
 */

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class MyThreadPoolExecutor {

    // 用 List 数据结构来存储线程
    private List<Thread> threadList = new ArrayList<>();

    // 是一个用来保存任务的队列
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);

    // 线程是否关闭的标志
    private volatile boolean isShutdown = false;

    // 通过 n 指定创建多少个线程
    public MyThreadPoolExecutor (int n) {
        for (int i = 0; i < n; i++) {
            Thread t = new Thread(() -> {
                // 线程要做的事情是 把任务队列中的任务不停的取出来，并且进行执行
                while (!isShutdown) {
                    try {
                        // 此处的 take 是带有阻塞功能的
                        // 如果队列为空，此处的 take 会阻塞
                        Runnable runnable = queue.take();
                        // 取出一个任务执行一个任务
                        runnable.run();
                    } catch (InterruptedException e){
                        // 当捕捉到 异常的时候，恢复线程的中断状态并退出循环
                        Thread.currentThread().interrupt();
                        break;
                    }
                }
            });
            t.start();
            threadList.add(t);
        }
    }

    // 将新任务添加到任务队列里面！
    public void submit(Runnable runnable) throws InterruptedException {
        if (isShutdown) {
            throw new IllegalStateException("线程池已经关闭，无法提交新的任务");
        }
        queue.put(runnable);
    }

    public void shutdown() {
        isShutdown = true;
        for (Thread t : threadList) {
            t.interrupt();
        }
    }
}
public class ThreadDemo43 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPoolExecutor executor = new MyThreadPoolExecutor(4);
        for (int i = 0; i < 1000; i++) {
            int n = i;
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("执行任务 " + n + "当前线程为：+ " + Thread.currentThread().getName());
                }
            });
        }
        Thread.sleep(5000);
        executor.shutdown();
    }
}
